<?php 
namespace App\Http\Controllers\Admin;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Ifsnop\Mysqldump as IMysqldump;

class DataController extends Controller{
	function recovery(){
		return view('admin.data.recovery');
	}
	function dorecovery(Request $request){
		//接收是否下载
		$isload = $request->get('isload');
		//到.env中拿
		$host = getenv('DB_HOST');
		$username = getenv('DB_USERNAME');
		$pw = getenv('DB_PASSWORD');
		$dname = getenv("DB_DATABASE");
		//生成数据库的备份文件 mysqldump -hip地址 -u用户名 -p密码 数据库名称>
		$path = storage_path('database');
		$filename = "database_".date('Y-m-d_H-i-s').".sql";
		# composer require ifsnop/mysqldump-php:2.*
		$dump = new IMysqldump\Mysqldump("mysql:host=$host;dbname=$dname", $username, $pw,array('add-drop-table'=>true));
		$dump->start("$path/$filename");
		if($isload == 2){
			//下载
			return response()->download($path.'/'.$filename,'database.sql');
		}else{
			return redirect()->back()->with("message","数据库备份成功，在服务器上生成了一个文件：$filename");
		}
	}
	function backup(){
		//读文件夹storage/database
		$path = storage_path('database');
		$dir = opendir($path);
		$arr = [];
		while($content = readdir($dir)){
			if($content != '.' && $content != '..'){
				$arr[]=$content;
			}
			
		}
		return view('admin.data.backup',['arr'=>$arr]);
	}
	function dobackup(Request $request){
		//接收选择的文件名称
		$filename = $request->get('filename');
		//读文件中内容
		$content=file_get_contents(storage_path('database').'/'.$filename);
		//获取sql语句
		preg_match_all("/DROP.*?;/",$content, $arr1);
		foreach($arr1[0] as $sql){
			$re = DB::statement($sql);
		}
		preg_match_all("/CREATE.*?;/s",$content, $arr2);
		foreach($arr2[0] as $sql){
			$re = DB::statement($sql);
		}
		preg_match_all("/INSERT.*?;/s",$content, $arr3);
		foreach($arr3[0] as $sql){
			$re = DB::statement($sql);
		}
		return redirect()->back()->with('message',"数据库恢复完成！");
	}
}